package com.example.customizedgroupmessage;

import java.util.ArrayList;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.telephony.SmsManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.*;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SMSSendActivity extends Activity {

	public static final int REQUEST_CODE_SENDCOMPLETION=1111;

	DBHelper mHelper;
	SQLiteDatabase db;
	Cursor cursor;
	String phone;
	String message;
	int count = 0;
	
	int mValue;
	ProgressDialog mProgress;
	boolean mQuit;
	SMSThread mThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_send_activity);	

		count = 0;
		mQuit = false;

		// 보낼 메시지
		TextView textMsgView = (TextView) findViewById(R.id.textMsgView);
		textMsgView.setText("");
		
		for(int i =0; i < SMSTemplate.smsTemplate.analyzedMsg.length ; i++){
			if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#name")){
				Drawable d = getResources().getDrawable(R.drawable.name);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#status")){
				Drawable d = getResources().getDrawable(R.drawable.status);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#org")){
				Drawable d = getResources().getDrawable(R.drawable.org);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else if(SMSTemplate.smsTemplate.analyzedMsg[i].equals("#custom")){
				Drawable d = getResources().getDrawable(R.drawable.custom);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(SMSTemplate.smsTemplate.analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				textMsgView.append(sText);
			}
			else{
				textMsgView.append(SMSTemplate.smsTemplate.analyzedMsg[i]);
			}
		}

		// 받는 사람
		printReceivers();

		// 전송 버튼
		Button btnSMSSend = (Button)findViewById(R.id.btnSend);
		btnSMSSend.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				mValue = 0;
				showDialog(0);
				mThread = new SMSThread();
				mThread.start();
			}
		});

		// sms db 삭제
		//mHelper = new SMSDBHelper(SMSSendActivity.this);
		//db = mHelper.getWritableDatabase();
		//db.execSQL("DELETE FROM sms;");
		//db.execSQL("DROP TABLE IF EXISTS sms");
		//db.execSQL("TRUNCATE TABLE sms;");
		//mHelper.close();

	}

	
	@SuppressWarnings("deprecation")
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0:
			mProgress = new ProgressDialog(this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("문자 전송 중");
			mProgress.setMessage("Wait...");
			mProgress.setMax(count);
			mProgress.setCancelable(false);	// Back 버튼으로 닫을 수 없음
			
			/*
			mProgress.setButton("Cancel", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					mQuit = true;
					dismissDialog(0);
				}
			});
			*/
			
			return mProgress;
		}
		return null;
	}

	
	Handler mHandler = new Handler() {
		@SuppressWarnings("deprecation")
		public void handleMessage(Message msg) {
			mValue = msg.arg1;
			if (mValue < count) {
				mProgress.setProgress(mValue);
			} else {
				mQuit = true;
				dismissDialog(0);
				Intent intent = new Intent(getBaseContext(), SendCompletion.class);
				startActivityForResult(intent, REQUEST_CODE_SENDCOMPLETION);
			}
		}
	};

	
	class SMSThread extends Thread {
		public void run() {

			mHelper = new DBHelper(SMSSendActivity.this);
			db = mHelper.getWritableDatabase();

			cursor = db.rawQuery("SELECT phone, name, status, organization, groupname, custom FROM sms", null);
			while (cursor.moveToNext()) {
				// 변환할 데이터 설정
				SMSTemplate.smsTemplate.setName(cursor.getString(1)); // name
				if(cursor.getString(2)!=null){ // status
					SMSTemplate.smsTemplate.setStatus(cursor.getString(2));
				}
				if(cursor.getString(3)!=null){ // organization
					SMSTemplate.smsTemplate.setOrganization(cursor.getString(3));
				}
				else{ // organ 없을 시 group name 사용
					SMSTemplate.smsTemplate.setOrganization(cursor.getString(4));
				}
				if(cursor.getString(5)!=null){ // custom
					SMSTemplate.smsTemplate.setCustom(cursor.getString(5));
				}

				phone = cursor.getString(0); // 전화번호
				message = SMSTemplate.smsTemplate.translate(); // 변환한 메시지

				sendSMS(phone, message);
				
				mValue++;
				Message msg = mHandler.obtainMessage();
				msg.arg1 = mValue;
				mHandler.sendMessage(msg);
				try { Thread.sleep(500); } catch (InterruptedException e) {;}
			}
			cursor.close();
		}
	}


	// 단문과 장문 구분하여 문자 전송
	private void sendSMS(String reciver , String content){		
		SmsManager smsManager = SmsManager.getDefault();

		if(content.getBytes().length > 80) { //장문
			ArrayList<String> parts = smsManager.divideMessage(content);
			smsManager.sendMultipartTextMessage(reciver, null, parts, null, null);
			for(int i=0; i<parts.size(); i++){
				insertMsgIntoSendBox(SMSSendActivity.this, phone, parts.get(i).toString()); // 디바이스의 SMS 데이터베이스에 값을 입력
			}
		}
		else { //단문일 경우 메시지를 SMS로 보냄.
			smsManager.sendTextMessage(reciver, null, content, null, null); 
			insertMsgIntoSendBox(SMSSendActivity.this, phone, message); // 디바이스의 SMS 데이터베이스에 값을 입력
		}
	}
	
	

	
/*	
	// 문자 전송
	private void sendSMS(String reciver , String content){
		Intent sentIntent = new Intent("SENT_SMS_ACTION");
		PendingIntent sentPI= PendingIntent.getBroadcast(getApplicationContext(),0, sentIntent,0);
		Intent deliveryIntent= new Intent("DELIVERED_SMS_ACTION");
		PendingIntent deliverPI= PendingIntent.getBroadcast(getApplicationContext(), 0, deliveryIntent,0);

		registerReceiver(new BroadcastReceiver() { 
			@Override
			public void onReceive(Context context, Intent intent) {
				// TODO Auto-generated method stub
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					// 전송 성공
					Toast.makeText(SMSSendActivity.this,  phone+"\n"+message+"\n"+"전송 성공", Toast.LENGTH_SHORT).show();
					insertMsgIntoSendBox(SMSSendActivity.this, phone, message); // 디바이스의 SMS 데이터베이스에 값을 입력
					//isSent = true;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					// 전송 실패
					Toast.makeText(SMSSendActivity.this,  phone+"\n"+message+"\n"+"전송 실패!!!", Toast.LENGTH_SHORT).show();
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					// 무선 꺼짐
				case SmsManager.RESULT_ERROR_NULL_PDU:
					// PDU 실패
				}
			}
		}, new IntentFilter("SENT_SMS_ACTION"));

		SmsManager.getDefault().sendTextMessage(reciver, null, content, sentPI, deliverPI);
	}
*/

	
	
	
	// 디바이스의 SMS 데이터베이스에 값을 입력
	private void insertMsgIntoSendBox(Context context, String sendNumber, String rcvMessage) {
		ContentValues values = new ContentValues();
		values.put("address", sendNumber);
		values.put("body", rcvMessage);
		context.getContentResolver().insert(Uri.parse("content://sms/sent"), values);
	}
	
	
	
	
	
	// 받는 사람 출력
	private void printReceivers(){
		TextView textRecieverView = (TextView) findViewById(R.id.textRecieverView);
		textRecieverView.setText("");

		mHelper = new DBHelper(this);
		db = mHelper.getWritableDatabase();
		SpannableStringBuilder ssb;
		int color = Color.GRAY;
		cursor = db.rawQuery("SELECT name, status, organization, groupname, phone FROM sms", null);

		while (cursor.moveToNext()) {
			textRecieverView.append(cursor.getString(0)); // name

			StringBuffer strBuf = new StringBuffer();
			if(cursor.getString(1)!=null){ // status
				strBuf.append(" "+cursor.getString(1));
			}

			if(cursor.getString(2)!=null){ // organization
				strBuf.append("("+cursor.getString(2)+")  ");
			}
			else{ // organ 없을 시 group name 사용
				strBuf.append("("+cursor.getString(3)+")  ");
			}

			ssb = new SpannableStringBuilder(strBuf.toString());
			ssb.setSpan(new ForegroundColorSpan(color), 0, strBuf.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			textRecieverView.append(ssb);
			count++;
		}
		cursor.close();
		mHelper.close();

		TextView textRecieverCount = (TextView) findViewById(R.id.textView2);
		textRecieverCount.setText("받는 사람 (" +count+"명)");
	}
	
}





